package web.servlet.logincheckcode.web;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author Administrator
 * @Date 2020/6/4 15:48
 **/
@WebServlet("/checkeCode")
public class CheckeCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /** 创建图片对象
         * 使用画笔
         * 填充背景颜色
         * 画边框
         * 写字符（随机产生）
         * 画干扰线*/
        int width = 80;
        int height = 30;

        BufferedImage Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = Image.getGraphics();
        g.setColor(Color.PINK);
        /*填充背景色*/
        g.fillRect(0,0,width,height);
        /*画边框*/
        g.setColor(Color.BLACK);
        g.drawRect(0,0,width-1,height-1);
        String s="zxcvbnmasdfghjklpoiuytrewq1234560789ZXCVBNMLKIHGFDSAOPUYTREWQ";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i <4 ; i++) {
            int index = random.nextInt(s.length());
            char ch = s.charAt(index);
            sb.append(ch);
        }
        request.getSession().setAttribute("session_code",sb.toString());
        g.setColor(Color.BLACK);
        g.drawString(sb.toString(),20,20);
        g.setFont(new Font("宋体",Font.BOLD,22));
        ImageIO.write(Image, "jpg", response.getOutputStream());

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
